package com.es.disped.web.controller.role;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.role.RoleService;
import com.es.disped.api.userrole.UserRoleRelService;
import com.es.disped.common.constant.RecordStatus;
import com.es.disped.common.model.MsgModel;
import com.es.disped.core.annotation.LogInject;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.model.Role;
import com.es.disped.dao.model.RoleExample;
import com.es.disped.dao.model.RoleNode;
import com.es.disped.dao.model.RoleType;
import com.es.disped.dao.model.UserRoleRelExample;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author Anson<br>
 *
 * Copyright by EasyShare 2019<br>
 *
 * All right reserved<br>
 *
 * Created on 下午5:00:13<br>
 *
 * 名称：RoleController.java<br>
 *
 * 描述：角色管理<br>
 */
@Api(value="角色管理")
@Controller
@RequestMapping("/manage/role")
public class RoleController extends BaseController{

	private static final String NAMESPACE="com.es.disped.dao.mapper.role.RoleCustomMapper";
	
	@LogInject
	private static Logger log;
	
	@Autowired
	RoleService roleService;
	
	@Autowired
	UserRoleRelService userRoleRelService;
	
	@ApiOperation(value="新增角色",httpMethod="POST",response=MsgModel.class,notes="新增角色-管理端")
	@RequiresPermissions(value= {"admin:save","sys:save"},logical=Logical.OR)
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@Transactional
	public @ResponseBody MsgModel save(@RequestBody @ApiParam(name="role",value="角色对象",required=true) Role role)
	{
		int count=0;
		if(Optional.of(role)
				.filter(name->role.getRoleName()!=null)
				.filter(parentId->role.getRoleParentId()!=null)
				.filter(code->role.getRoleCode()!=null)
				.isPresent())
		{
			role.setRoleId(getUUID());
			role.setRoleType(RoleType.ROLE.getValue());
			role.setRoleValid(RecordStatus.USEAGE.getValue());
			count=roleService.insertSelective(role);
			//修改角色父类节点类型
			Role oldParentNode=roleService.selectByPrimaryKey(role.getRoleParentId());
			if(RoleType.ROLE.getValue().equals(oldParentNode.getRoleType()))
			{
				Role parentNode=new Role();
				parentNode.setRoleType(RoleType.GROUP.getValue());
				RoleExample roleExample=new RoleExample();
				roleExample.createCriteria().andRoleIdEqualTo(oldParentNode.getRoleId());
				roleService.updateByExampleSelective(parentNode, roleExample);
			}
		}
		log.debug(count==1?HttpStatus.OK.value()+"-角色写入成功":
			HttpStatus.EXPECTATION_FAILED.value()+"-保存失败",role);
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"角色写入成功":"保存失败", role);
	}
	
	@ApiOperation(value="更新角色",httpMethod="POST",response=MsgModel.class,notes="更新角色-管理端")
	@RequiresPermissions(value= {"admin:update","sys:update"},logical=Logical.OR)
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public @ResponseBody MsgModel update(@RequestBody @ApiParam(name="role",value="角色对象",required=true) Role role)
	{
		int count=0;
		if(Optional.of(role)
				.filter(id->role.getRoleId()!=null)
				.isPresent())
		{
			count=roleService.updateByPrimaryKeySelective(role);
		}
		log.debug(count==1?HttpStatus.OK.value()+"-角色更新成功":
			HttpStatus.EXPECTATION_FAILED.value()+"-角色更新失败",role);
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"角色更新成功":"角色更新失败", role);
	}
	
	@ApiOperation(value="删除角色",httpMethod="POST",response=MsgModel.class,notes="删除角色-系统端")
	@RequiresPermissions(value= {"admin:delete","sys:delete"},logical=Logical.OR)
	@Transactional
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public @ResponseBody MsgModel delete(@RequestBody @ApiParam(name="role",value="角色对象",required=true) Role role)
	{
		int relCount=0,roleCount=0;
		if(Optional.of(role)
				.filter(rId->role.getRoleId()!=null)
				.filter(rpId->role.getRoleParentId()!=null)
				.isPresent())
		{
			//删除角色引用
			UserRoleRelExample userRoleRelExample=new UserRoleRelExample();
			userRoleRelExample.createCriteria().andRoleIdEqualTo(role.getRoleId());
			relCount=userRoleRelService.deleteByExample(userRoleRelExample);
			//删除角色节点及子节点
			RoleExample roleExample=new RoleExample();
			roleExample.createCriteria().andRoleParentIdEqualTo(role.getRoleId());
			roleCount+=roleService.deleteByExample(roleExample);
			roleCount+=roleService.deleteByPrimaryKey(role.getRoleId());
			//修改当前角色父节点类型
			RoleExample parentExample=new RoleExample();
			parentExample.createCriteria().andRoleParentIdEqualTo(role.getRoleParentId());
			List<Role> list=roleService.selectByExample(parentExample);
			if(this.isNull(list))
			{
				Role parentNode=new Role();
				parentNode.setRoleType(RoleType.ROLE.getValue());
				RoleExample parentRoleExample=new RoleExample();
				parentRoleExample.createCriteria().andRoleIdEqualTo(parentNode.getRoleId());
				roleService.updateByExampleSelective(parentNode, parentRoleExample);
			}
		}
		log.debug(roleCount>=1?HttpStatus.OK.value()+"-角色删除成功,共删除"+roleCount+"个角色，"+relCount+"个引用":
			   HttpStatus.EXPECTATION_FAILED.value()+"-角色删除失败,共删除"+roleCount+"个角色，"+relCount+"个引用");
		return new MsgModel(roleCount>=1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				roleCount>=1?"角色删除成功,共删除"+roleCount+"个角色，"+relCount+"个引用":"角色删除失败");
	}
	
	
	
	@ApiOperation(value="角色检索",httpMethod="POST",response=MsgModel.class,notes="角色检索-系统端")
	@RequestMapping(value="/list",method=RequestMethod.POST)
	public @ResponseBody MsgModel list(@RequestBody @ApiParam(name="role",value="角色对象",required=false) Role role)
	{
		RoleExample roleExample=new RoleExample();
		if(!this.isNull(role.getRoleName()))
		{
			roleExample.createCriteria().andRoleNameLike("%"+role.getRoleName()+"%"); 
		}
		if(!this.isNull(role.getRoleId()))
		{
			roleExample.createCriteria().andRoleIdEqualTo(role.getRoleId());
		}
		List<Role> roles=roleService.selectByExample(roleExample);
		return new MsgModel(roles.size()>0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				roles.size()>0?"":"角色检索不到", roles.size()>0?roles:"");
	}
	
//	@ApiOperation(value="角色分页查询",httpMethod="POST",response=MsgModel.class,notes="角色分页查询-系统端")
//	@RequiresPermissions(value= {"admin:select","sys:select"},logical=Logical.OR)
//	@RequestMapping(value="/pages",method=RequestMethod.POST)
//	public @ResponseBody MsgModel pages(@RequestBody @ApiParam(name="paramMap",value="分页查询参数[offset,limit]",required=true) Map<String, Object> paramMap)
//	{
//		RoleExample roleExample=new RoleExample();
//		PageModel<Role> pageModel=null;
//		if(Optional.of(paramMap)
//				.filter(offset->paramMap.containsKey("offset")!=false)
//				.filter(limit->paramMap.containsKey("limit")!=false)
//				.isPresent())
//		{
//			pageModel=roleService.selectByExampleForOffsetPage(roleExample,
//					Integer.valueOf(paramMap.get("offset").toString()), Integer.valueOf(paramMap.get("limit").toString()));
//		}
//		return new MsgModel(pageModel!=null?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
//				pageModel!=null?"":"角色检索不到", pageModel!=null?pageModel:"");
//	}
	
	@ApiOperation(value="获取角色Tree结构列表",httpMethod="POST",response=MsgModel.class,notes="根据角色ID对应节点向下检索拉取Tree，id可为null-系统端")
    @RequestMapping(value="/roleTree",method=RequestMethod.POST)
    public @ResponseBody MsgModel getRoleTree(@RequestBody @ApiParam(name="paramMap",value="当前检索的Tree的起始节点ID，若默认为空则从根节点开始",required=false) Map<String, Object> paramMap)
    {
		if (!paramMap.containsKey("id")) {
            paramMap.put("id", "00000000000000000000000000000000");
        }
        List<RoleNode> nodeList = new ArrayList<>();
        List<RoleNode> rootList = this.getService().selectList(NAMESPACE+".getRoleNode", paramMap.get("id"));
        for (RoleNode roleNode : rootList) {
            roleNode.setChildren(getRoleNode(roleNode.getId()));
            nodeList.add(roleNode);
        }
        return new MsgModel(nodeList.size()>0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
        		nodeList.size()>0?"":"列表加载失败", nodeList.size()>0?nodeList:"");
    }

	/**
     * 角色 tree 结构加载<br>
     *
     * @param pid 父Id
     * @return List<RoleNode> 角色节点列表集合
     */
    private List<RoleNode> getRoleNode(String pid) {
    	 List<RoleNode> roleList = this.getService().selectList(NAMESPACE+".getRoleNode", pid);
         return roleList;
	}
    
    
}
